<?php

class RSSAggregator {

	protected $feedcontents = array();
	protected $destencoding = "UTF-8";

	/**
	 *
	 * @param array  $feeds Array of feeds to aggregate
	 * @param string $destencoding Encoding to change to
	 */
	public function __construct($feeds, $destencoding) {
		$this->destencoding = $destencoding;
		$this->load($feeds);
	}

	public function changeEncoding($str, $destenc, $sourceenc) {
		if (strtolower($sourceenc) == strtolower($destenc)) return $str;
		//return mb_convert_encoding($str, $destenc, $sourceenc);
		return utf8_decode($str);
	}

	public function load ($feeds) {
		if (is_array($feeds))
		foreach ($feeds as $feed) {
			$feedxmlstring = file_get_contents($feed);
			preg_match('/<\?xml.*?encoding="(.*?)".*?\?>/', $feedxmlstring, $matches);
			$encoding = !$matches[1]?$this->destencoding:$matches[1];
			$feedxml = new SimpleXMLElement($feedxmlstring);
			foreach ($feedxml->channel[0]->item as $item) {
				$this->feedcontents[] = array(
					'title' => $this->changeEncoding((string) $item->title, $this->destencoding, $encoding),
					'pubDate' => strtotime($item->pubDate),
					'description' => $this->changeEncoding((string) $item->description, $this->destencoding, $encoding),
					'link' => (string) $item->link
				);
			}
		}
		usort($this->feedcontents, array($this, 'sort_cmp'));
	}

	protected function sort_cmp($a, $b) {
		if ($a['pubDate']==$b['pubDate']) return 0;
		return $a['pubDate']<$b['pubDate']?1:-1;
	}

	public function result() {
		return $this->feedcontents;
	}



}

$cachefile = $_SERVER['DOCUMENT_ROOT'].'/cachefile';
if (is_file($cachefile)) {
	$stat = filemtime($cachefile);
} else {
	$stat = 0;
}
if (!is_file($cachefile) || $stat + 3600 < time()) { // now + 3h
	$rssaggr = new RSSAggregator(array(
		'http://www.ftd.de/rss2/finanzen/maerkte',
		'http://www.ftd.de/rss2/finanzen/investmentfonds',
		'http://www.ftd.de/rss2/finanzen/alternativen',
		'http://www.ftd.de/rss2/karriere-management/recht-steuern'
	), 'ISO-8859-1');
	file_put_contents($cachefile, serialize($rssaggr->result()));
}
$results = unserialize(file_get_contents($cachefile));

$counter = 0;
print '<div id="ticker">';
print '<ul id="listticker">';
foreach ($results as $result) {
	$counter++;
	print '<li><span class="rssdate">'.date('d.m.y: H:i:s', $result['pubDate']).'</span><br/><a href="'.$result['link'].'">'.$result['title'].'</a></li>';
	if ($counter>=30) break;
}
print "</ul>";
print "</div>";

